package me.zhengjie.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import me.zhengjie.annotation.Log;
import me.zhengjie.dao.*;
import me.zhengjie.server.MaterialDetailService;
import me.zhengjie.server.MaterialService;
import me.zhengjie.server.TransferOrderService;
import me.zhengjie.utils.HttpUtil;
import me.zhengjie.utils.PageResult;
import me.zhengjie.vo.Result;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.Date;
import java.util.List;

@RestController
@RequiredArgsConstructor
@Api(tags = "调拨单管理")
@RequestMapping("/api/transferOrder")
public class TransferOrderController {

    private final TransferOrderService transferOrderService;

    private final MaterialDetailService materialDetailService;

    private final MaterialService materialService;

    @GetMapping(value = "list")
    @Log("调拨单列表")
    @ApiOperation("查询调拨单")
    public ResponseEntity<PageResult<TransferOrderDao>> queryOutBoundOrder(TransferOrderDao criteria, Page<Object> page){
        return new ResponseEntity<>(transferOrderService.queryAll(criteria,page), HttpStatus.OK);
    }

    @GetMapping(value = "listDetail")
    @Log("查询调拨单详情")
    @ApiOperation("查询调拨单详情")
    public ResponseEntity<TransferOrderDetailDao> queryOutBoundOrderDetail( String transferCode ){
        return new ResponseEntity<>(transferOrderService.queryDetail(transferCode), HttpStatus.OK);
    }



    @PostMapping("/order/dispatch")
    @Log("新增outBound")
    @ApiOperation("新增outBound")
    @Transactional
    public Result createOutBoundOrder(@RequestBody TransferOrderDao resources) {
        try {
            //如果查到调拨单就不添加
            List<TransferOrderDao> list = transferOrderService.list(new LambdaQueryWrapper<TransferOrderDao>().eq(TransferOrderDao::getCode, resources.getCode()));
            if (!list.isEmpty()) {
                throw new RuntimeException("此调拨单已存在");
            }
            List<MaterialDetailDao> materialDetails = parseMaterialList(resources.getMaterialList());
            resources.setCreateTime(new Date());
            resources.setMaterialList(resources.getMaterialList());
            if (!materialDetails.isEmpty()) {
                // 设置关联关系并批量保存
                for (MaterialDetailDao materialDetail : materialDetails) {
                    materialDetails.forEach(detail -> detail.setTransferId(resources.getCode()));
                    materialDetails.forEach(detail -> detail.setTargetLocation(resources.getDestination()));
                    List<MaterialDao> materialDaos = materialService.list(new LambdaQueryWrapper < MaterialDao > ().eq(MaterialDao::getMaterialCode, materialDetail.getMaterialCode()));
                    if (materialDaos.isEmpty()) {
                        throw new RuntimeException("该物料为空");
                    }
                    materialDetails.forEach(detail -> detail.setUnit(materialDaos.get(0).getUnit()));
                    materialDetails.forEach(detail -> detail.setUnIssuedWeight(materialDetail.getUnIssuedWeight()));
                    materialDetails.forEach(detail -> detail.setIssuedWeight(0.00));
                    materialDetailService.save(materialDetail);
                }
            }
            transferOrderService.save(resources);
            return Result.successmes();
        } catch (JsonProcessingException e) {
            return Result.fail("系统出错，请重试");
        }
    }

    // JSON解析独方法
    private List<MaterialDetailDao> parseMaterialList(String json) throws JsonProcessingException {
        if (json == null || json.trim().isEmpty()) {
            return Collections.emptyList();
        }
        ObjectMapper mapper = new ObjectMapper();
        JavaType type = mapper.getTypeFactory().constructCollectionType(List.class, MaterialDetailDao.class);
        return mapper.readValue(json, type);
    }

    @PostMapping(value = "lockCode")
    @Log("锁定transferOrderDao")
    @ApiOperation("锁定transferOrderDao")
    public Result<Object> lockOutBoundOrder(@Validated @RequestBody TransferOrderDao resources){
        resources.setStatus(2);
        return Result.success(transferOrderService.updateById(resources));
    }
    @PostMapping(value = "unlock")
    @Log("解锁transferOrderDao")
    @ApiOperation("解锁transferOrderDao")
    public Result<Object> unlockOutBoundOrder(@Validated @RequestBody TransferOrderDao resources){
        resources.setStatus(0);
        return Result.success(transferOrderService.updateById(resources));
    }
    @PostMapping (value = "closeCode")
    @Log("取消出库transferOrderDao")
    @ApiOperation("取消出库transferOrderDao")
    public Result<Object> deleteOutBoundOrder(@Validated @RequestBody TransferOrderDao resources){
        resources.setStatus(4);
        try {
            return Result.success(transferOrderService.updateForStatus(resources));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping(value = "closed")
    @Log("结案transferOrderDao")
    @ApiOperation("结案transferOrderDao")
    public Result<Object> closedOutBoundOrder( @RequestBody TransferOrderDao resources){
        resources.setStatus(3);
        boolean b = transferOrderService.updateById(resources);
            return Result.success(b);
    }


    @PostMapping(value = "hand/closed")
    @Log("手动强制结束出库单")
    @ApiOperation("手动强制结束出库单")
    public ResponseEntity<Object> handClosedOutBoundOrder( @RequestBody ClosedOutBoundOrderDao resources ){
        return new ResponseEntity<>(transferOrderService.updateOutBandCodeById(resources),HttpStatus.OK);
    }

    @PostMapping(value = "hand/closedTransferOrder")
    @Log("手动强制结束调拨单")
    @ApiOperation("手动强制结束调拨单")
    public ResponseEntity<Object> handClosedTransferOrder( @RequestBody ClosedTransferOrderOrderDao resources ){
        return new ResponseEntity<>(transferOrderService.handClosedTransferOrder(resources),HttpStatus.OK);
    }


}
